package com.ruoyi.system.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.Dailyschedule;
import com.ruoyi.system.mapper.DailyscheduleMapper;
import com.ruoyi.system.service.IDailyscheduleService;
import com.ruoyi.system.utils.Upload;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 作息时间解析Service业务层处理
 *
 * @author ruoyi
 * @date 2024-03-24
 */
@Slf4j
@Service
public class DailyscheduleServiceImpl implements IDailyscheduleService {
    @Autowired
    private DailyscheduleMapper dailyscheduleMapper;

    /**
     * 上传作息时间表并解析
     *
     * @param file    文件
     * @param isCover 是否覆盖 1:覆盖 0:取消
     * @return
     * @throws IOException
     */
    @Override
    public int uploadAndSaveCourse(MultipartFile file, int isCover) throws IOException {
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        log.info("拿到文件后缀 = " + suffix);
        if (!suffix.equals(".xlsx")) {
            log.error("上传文件失败,请检查格式,文件需为.xlsx类型");
            return 4;
        }
        XSSFWorkbook wb1 = new XSSFWorkbook(file.getInputStream());
        Dailyschedule dailyschedule = new Dailyschedule();
        List<String> timePeriodList = Lists.newArrayList();
        List<String> startTimeList = Lists.newArrayList();
        List<String> endTimeList = Lists.newArrayList();
        List<String> contentList = Lists.newArrayList();
        String[][] result;
        try {
            // 获取Excel表文件里的数据
            //第二个参数为从Excel文件里第几行开始读
            result = Upload.getFullData(wb1, 0);

            for (int i = 0; i < result.length; i++) {
                for (int j = 0; j < result[i].length - 1; j++) {
                    log.info("result[i][j] = " + "result[" + i + "][" + j + "] = " + result[i][j]);
                }

                if (i == 0) {
                    String yq = result[i][0];
                    String pattern = "([1-9]\\d*)|([零|一|二|三|四|五|六|七|八|九|十]+)|([春|夏|秋|冬]+)";

                    Pattern r = Pattern.compile(pattern);
                    Matcher m = r.matcher(yq);
                    int f = 0;
                    while (m.find()) {
                        switch (f) {
                            case 0:
                                dailyschedule.setYearTime(m.group().trim());
                                break;
                            case 1:
                                dailyschedule.setSeason(m.group().trim());
                                break;
                            default:
                                break;
                        }
                        f++;
                    }
                }

                if (i > 1) {
                    timePeriodList.add(result[i][0]);
                    startTimeList.add(result[i][1]);
                    endTimeList.add(result[i][2]);
                    contentList.add(result[i][3]);
                }
            }

            //年度、和季度都不能为空
            if (StringUtils.isEmpty(dailyschedule.getYearTime()) || StringUtils.isEmpty(dailyschedule.getSeason())) {
                return 5;
            }

            //上传的时间表内容，已经存在
            List<Dailyschedule> dailyscheduleList = dailyscheduleMapper.selectDailyscheduleList(dailyschedule);
            if (1 == isCover) { //覆盖
                if (StringUtils.isNotEmpty(dailyscheduleList)) {
                    int i = dailyscheduleMapper.deleteDailyscheduleById(dailyscheduleList.get(0).getId());
                    log.info("删除时间表成功， 共删除： " + i);
                }
            } else { //不覆盖
                if (StringUtils.isNotEmpty(dailyscheduleList) && dailyscheduleList.size() > 0) return 3;
            }

            dailyschedule.setTimePeriod(JSONObject.toJSONString(timePeriodList));
            dailyschedule.setStartTime(JSONObject.toJSONString(startTimeList));
            dailyschedule.setEndTime(JSONObject.toJSONString(endTimeList));
            dailyschedule.setContent(JSONObject.toJSONString(contentList));

            dailyscheduleMapper.insertDailyschedule(dailyschedule);
            log.info("添加时间表信息完成");
        } catch (Exception e) {
            log.error("时间表导入失败", e);
        } finally {
            wb1.close();
        }

        return 1;
    }

    /**
     * 查询作息时间解析
     *
     * @param id 作息时间解析主键
     * @return 作息时间解析
     */
    @Override
    public Dailyschedule selectDailyscheduleById(Long id) {
        return dailyscheduleMapper.selectDailyscheduleById(id);
    }

    /**
     * 查询作息时间解析列表
     *
     * @param dailyschedule 作息时间解析
     * @return 作息时间解析
     */
    @Override
    public List<Dailyschedule> selectDailyscheduleList(Dailyschedule dailyschedule) {
        return dailyscheduleMapper.selectDailyscheduleList(dailyschedule);
    }

    /**
     * 新增作息时间解析
     *
     * @param dailyschedule 作息时间解析
     * @return 结果
     */
    @Override
    public int insertDailyschedule(Dailyschedule dailyschedule) {
        dailyschedule.setCreateTime(DateUtils.getNowDate());
        return dailyscheduleMapper.insertDailyschedule(dailyschedule);
    }

    /**
     * 修改作息时间解析
     *
     * @param dailyschedule 作息时间解析
     * @return 结果
     */
    @Override
    public int updateDailyschedule(Dailyschedule dailyschedule) {
        dailyschedule.setUpdateTime(DateUtils.getNowDate());
        return dailyscheduleMapper.updateDailyschedule(dailyschedule);
    }

    /**
     * 批量删除作息时间解析
     *
     * @param ids 需要删除的作息时间解析主键
     * @return 结果
     */
    @Override
    public int deleteDailyscheduleByIds(Long[] ids) {
        return dailyscheduleMapper.deleteDailyscheduleByIds(ids);
    }

    /**
     * 删除作息时间解析信息
     *
     * @param id 作息时间解析主键
     * @return 结果
     */
    @Override
    public int deleteDailyscheduleById(Long id) {
        return dailyscheduleMapper.deleteDailyscheduleById(id);
    }
}
